package org.hxzon.demo.jt.logsearcher.util;

import org.apache.lucene.search.highlight.Formatter;
import org.apache.lucene.search.highlight.TokenGroup;

public class MyHighlighterFormatter implements Formatter {

    private static final String DEFAULT_PRE_TAG = "<span>";
    private static final String DEFAULT_POST_TAG = "</span>";

    private String preTag;
    private String postTag;

    public MyHighlighterFormatter(String preTag, String postTag) {
        this.preTag = preTag;
        this.postTag = postTag;
    }

    public MyHighlighterFormatter() {
        this(DEFAULT_PRE_TAG, DEFAULT_POST_TAG);
    }

    @Override
    public String highlightTerm(String originalText, TokenGroup tokenGroup) {
        if (tokenGroup.getTotalScore() <= 0) {
            return originalText;
        }

        // Allocate StringBuilder with the right number of characters from the
        // beginning, to avoid char[] allocations in the middle of appends.
        StringBuilder returnBuffer = new StringBuilder(preTag.length() + originalText.length() + postTag.length());
        returnBuffer.append(preTag);
        returnBuffer.append(originalText);
        returnBuffer.append(postTag);
        return returnBuffer.toString();
    }

}
